<?php

namespace App\Services\Warehouse\Services;

use App\Services\Warehouse\Interfaces\EquipmentServiceInterface;
use App\Services\Warehouse\Model\Equipment;
use Illuminate\Support\Facades\Auth;
use App\Exceptions\ApiV2Exception;

class EquipmentService implements EquipmentServiceInterface
{
    public function index($request)
    {
        $equipmentCode = $request['equipmentCode'] ?? '';
        $equipmentName = $request['equipmentName'] ?? '';
        $brand = $request['brand'] ?? '';
        $model = $request['model'] ?? '';
        $location = $request['location'] ?? '';
        $size = $request['size'] ?? 50;
        $data = Equipment::query()
            ->when($equipmentCode, function ($query) use ($equipmentCode) {
                return $query->where('equipmentCode', 'like', '%' . $equipmentCode . '%');
            })
            ->when($equipmentName, function ($query) use ($equipmentName) {
                return $query->where('equipmentName', 'like', '%' . $equipmentName . '%');
            })
            ->when($brand, function ($query) use ($brand) {
                return $query->where('brand', $brand);
            })
            ->when($model, function ($query) use ($model) {
                return $query->where('model', $model);
            })
            ->when($location, function ($query) use ($location) {
                return $query->where('location', $location);
            })
            ->orderBy("updated_at", "desc")
            ->paginate($size);

        $data->appends($request);

        return $data->toArray();
    }

    public function set($request, $id = 0)
    {
        $equipmentCode = $request['equipmentCode'];
        if ($id) {
            $data = Equipment::query()->where('equipmentCode',$equipmentCode)->where('id','!=',$id)->first();
            if(!empty($data)){
                throw new ApiV2Exception("设备编码不能重复");
            }
            $data = Equipment::findOrFail($id);
        } else {
            $data = Equipment::query()->where('equipmentCode',$equipmentCode)->first();
            if(!empty($data)){
                throw new ApiV2Exception("设备编码不能重复");
            }
            $data = new Equipment();
        }
        $request['user_id'] = Auth::id();
        $data->fill($request)->save();
        return $data->toArray();
    }

    public function get($id)
    {
        return Equipment::query()->where('id', $id)->firstOrFail()->toArray();
    }

    public function destroy($id)
    {
        $data = Equipment::findOrFail($id);
        $data->delete();
    }
}
